from tadmin.models import Robot
import json
import time
from django.http import HttpResponse
from django.shortcuts import render

from rest_framework.viewsets import ModelViewSet
from tadmin.models import UserInfo, Menu
from tadmin.serializer import UserInfoSerializer
from tadmin.filter import UserInfoFilter
from django_filters.rest_framework import DjangoFilterBackend

from rest_framework.views import APIView
from django.http import JsonResponse

from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from django.http import HttpResponse

from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt

from channels.layers import get_channel_layer  
from asgiref.sync import AsyncToSync 

def create_token(username, expire=60 * 60):
    import jwt
    key = 'theyn'
    now = time.time()
    paylaod = {'username': username, 'exp': int(now + expire)}
    return jwt.encode(paylaod, key, algorithm='HS256')


@csrf_exempt
def login_view(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            token = create_token(username)
            resp = {
                'key1': 'true',
                'code': 200,
                'username': username,
                'data': {
                    'token': token
                }
            }
            return JsonResponse(resp)
            print("登录成功")
            data = {
                'key1': 'true',
                'key2': 'value2',
            }
            return JsonResponse(data)
            # return redirect('docs/')
        else:
            print("登录失败")
            data = {
                'key1': 'false',
                'key2': 'value2',
            }
            return JsonResponse(data)
            # return HttpResponse("Invalid username or password.")
    return HttpResponse("Hello world ! ")


def hello(request):
    data = request.GET
    pagenum = data.get('pagenum', 'default_value')
    print(pagenum)
    return HttpResponse("Hello world ! ")


def getRobots(request):  # 获取机器人列表
    data = request.GET
    pagenum = int(data.get('pagenum', 'default_value'))-1
    pagesize = int(data.get('pagesize', 'default_value'))
    print(pagenum*pagesize)
    print(pagenum*pagesize+pagesize)
    total = Robot.objects.count()
    obj = Robot.objects.filter(id__range=(
        pagenum*pagesize+1, pagenum*pagesize+pagesize)).values().order_by('device_number')
    robot_dicts = list(obj)
    # print(len(robot_dicts))
    data = {
        "data": {
            "robots": robot_dicts,
            "total": total,
        },
        "meta": {
            "msg": "获取机器人列表成功",
            "status": 200
        }
    }
    return JsonResponse(data)

    return HttpResponse("Hello world ! ")
def getOnlineRobots(request):  # 获取在线机器人列表
    obj = Robot.objects.filter(status_connect='已连接', is_active=True).values().order_by('device_number')
    robot_dicts = list(obj)
    data = {
        "data": {
            "robots": robot_dicts
        },
        "meta": {
            "msg": "获取在线机器人列表成功",
            "status": 200
        }
    }
    return JsonResponse(data)
@csrf_exempt
def activeRobot(request, robotId, is_active):  # 激活机器人
    is_active_str = is_active.lower()
    is_active = is_active_str == 'true'
    try:
        Robot.objects.filter(id=robotId).update(is_active=is_active)
        if is_active:
            msg = "激活机器人成功"
        else:
            msg = "禁用机器人成功"
        status = 200
    except Exception as e:
        print(e)
        if is_active:
            msg = "激活机器人失败"
        else:
            msg = "禁用机器人失败"
        status = 666
    data = {
        "data": [],
        "meta": {
            "msg": msg,
            "status": status
        }
    }
    return JsonResponse(data)


def debug(msg):
    print(msg)


def menu(request):
    # obj = Menu(data=data)
    # obj.save()
    obj = Menu.objects.get(id=7)
    # obj = Menu.objects.get()
    # obj = Menu.objects.all()
    # obj = Menu.objects.values()
    # print(type(obj))
    # print(obj)
    # print(type(obj.get_data()))
    data = obj.get_data()
    return JsonResponse(data)


class UserInfoViewSet(ModelViewSet):
    serializer_class = UserInfoSerializer

    filter_class = UserInfoFilter
    filter_fields = ['username']
    search_fields = ('username', )


class GetMessageView(APIView):
    # get 请求
    def get(self, request):
        # 获取参数数据
        get = request.GET
        # 获取参数 a
        a = get.get('a')
        print(str(a) + 'hlly')
        # 返回信息
        d = {
            'status': 1,
            'message': 'success',
        }
        return JsonResponse(d)


class start():
    print("哈利路亚startDjango")

    # # 获取channel layer
    # channel_layer = get_channel_layer()

    # # 发送消息到Layer
    # print("发送消息到Layer")
    # message = {"text": "Hello from Django"}
    # from AGV_WEB import consumers
    # # AsyncToSync(consumers.ChatConsumer.chat_message)(message)
    # AsyncToSync(channel_layer.group_send)(
    #     "my_group",
    #     {
    #         "type": "websocket.sendmessage",
    #         "message": "Hello from view!",
    #     }
    # )